package com.nuanshui.framework.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: <br/>
 * 网站: <a href="http://www.crazyit.org">疯狂ava联盟</a> <br/>
 * Copyright (C), 2001-2014, Yeeku.H.Lee <br/>
 * This program is protected by copyright laws. <br/>
 * Program Name: <br/>
 * Date:
 * 
 * @author Yeeku.H.Lee kongyeeku@163.com
 * @version 1.0
 */
@SuppressWarnings("deprecation")
public class HttpUtil {
	
	private static final Logger logger = LoggerFactory
			.getLogger(HttpUtil.class);
	
	/**
	 * 
	 * @param url
	 *            发送请求的URL
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	@SuppressWarnings({ "resource"})
	public static String getRequest(final String url) throws Exception {
			HttpClient httpClient = new DefaultHttpClient();
			// 创建HttpGet对象。
			HttpGet get = new HttpGet(url);
			//get.addHeader("User-Agent", "Dalvik/1.6.0 (Linux; U; Android 4.4.4; HM NOTE 1S MIUI/V6.4.5.0.KHKCNCB)");
			//get.addHeader("Host","api.wwmapp.cn");
			// 发送GET请求
			HttpResponse httpResponse = httpClient.execute(get);
			// 如果服务器成功地返回响应
			System.out.println(httpResponse.getStatusLine().getStatusCode());
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 获取服务器响应字符串
			 String	 result = EntityUtils.toString(httpResponse
						.getEntity());

				return result;
			}
			return null;
	}

	/**
	 * @param url
	 *            发送请求的URL
	 * @param rawParams
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public static String postRequest(final String url,
			final Map<String, Object> rawParams) throws Exception {
		 HttpClient httpClient = new DefaultHttpClient();
		// 创建HttpPost对象。
		HttpPost post = new HttpPost(url);
		// 如果传递参数个数比较多的话可以对传递的参数进行封装
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (String key : rawParams.keySet()) {
			// 封装请求参数
			params.add(new BasicNameValuePair(key, String.valueOf(rawParams
					.get(key))));
		}
		// 设置请求参数
		post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
		// 发送POST请求
		HttpResponse httpResponse = httpClient.execute(post);
		// 如果服务器成功地返回响应
		System.out.println(httpResponse.getStatusLine().getStatusCode());
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}

	
	/**
	 * @param url
	 *            发送请求的URL
	 * @param rawParams
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public static String post(final String url,
			final Map<String, String> rawParams) throws Exception {
		 HttpClient httpClient = new DefaultHttpClient();
		// 创建HttpPost对象。
		HttpPost post = new HttpPost(url);
		// 如果传递参数个数比较多的话可以对传递的参数进行封装
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (String key : rawParams.keySet()) {
			// 封装请求参数
			params.add(new BasicNameValuePair(key,rawParams.get(key)));
		}
		// 设置请求参数
		post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
		// 发送POST请求
		HttpResponse httpResponse = httpClient.execute(post);
		// 如果服务器成功地返回响应
		System.out.println(httpResponse.getStatusLine().getStatusCode());
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}
	
	@SuppressWarnings("resource")
	public static String jsonPostRequest(final String url,
			final Map<String, Object> rawParams) throws Exception {
		 HttpClient httpClient = new DefaultHttpClient();
		// 创建HttpPost对象。
		HttpPost post = new HttpPost(url);
		// 设置请求参数
		String json_string = JSON.toJSONString(rawParams);
		System.out.println(json_string);
        post.setEntity(new ByteArrayEntity(json_string.getBytes(),ContentType.APPLICATION_JSON));
        post.setHeader("Content-type", "application/json");
        // 发送POST请求
		HttpResponse httpResponse = httpClient.execute(post);
		// 如果服务器成功地返回响应
		System.out.println(httpResponse.getStatusLine().getStatusCode());
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}
	
	/**
	 * 设置文件头并post请求
	 * @param url
	 * @param rawParams
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public static String setHeaderAndPostRequest(final String url,
			final Map<String, Object> rawParams) throws Exception {
		 HttpClient httpClient = new DefaultHttpClient();
		// 创建HttpPost对象。
		HttpPost post = new HttpPost(url);
		post.addHeader("From", "TriData@sp.com");
		// 如果传递参数个数比较多的话可以对传递的参数进行封装
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (String key : rawParams.keySet()) {
			// 封装请求参数
			params.add(new BasicNameValuePair(key, String.valueOf(rawParams
					.get(key))));
		}
		// 设置请求参数
		post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
		// 发送POST请求
		HttpResponse httpResponse = httpClient.execute(post);
		// 如果服务器成功地返回响应
		System.out.println(httpResponse.getStatusLine().getStatusCode());
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}

	public static String requestByPostMethod(String url,String paramsName, String data) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String returnValues=null;
		try {
			HttpPost post = new HttpPost(url);          //这里用上本机的某个工程做测试
			//创建参数列表
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			list.add(new BasicNameValuePair(paramsName, data));
			//url格式编码
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
			post.setEntity(uefEntity);
			System.out.println("POST 请求...." + post.getURI());
			//执行请求
			CloseableHttpResponse httpResponse = httpClient.execute(post);
			HttpEntity entity = httpResponse.getEntity();
			if (null != entity) {
				returnValues=EntityUtils.toString(entity);
			}
		}  catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(httpClient!=null){
				try{
					httpClient.close();
				}catch(Exception e){
					e.printStackTrace();
				}

			}
		}
		return returnValues;
	}

	public static String postJson(String url, String data) {
		return postData(url,data,"application/json");
	}

	/**
	 * post 请求
	 *
	 * @param url
	 * @param xml
	 * @return
	 */
	public static String postXml(String url, String xml) {

		return postData(url,xml,"text/xml");
	}

	private static SslContextUtils sslContextUtils = new SslContextUtils();

	public static String sendXmlDataByPost(String postUrl, String xmlData) {
		StringBuilder sb = new StringBuilder();
		try {
			URL url = new URL(postUrl);
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

			if (httpConn instanceof HttpsURLConnection) {
				sslContextUtils.initHttpsConnect((HttpsURLConnection) httpConn);
			}
			httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			httpConn.setRequestMethod("POST");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setRequestProperty("Content-type", "text/xml");
			httpConn.setConnectTimeout(60000);
			httpConn.setReadTimeout(60000);
			// 发送请求
			httpConn.getOutputStream().write(xmlData.getBytes("utf-8"));
			httpConn.getOutputStream().flush();
			httpConn.getOutputStream().close();
			// 获取输入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
			char[] buf = new char[1024];
			int length = 0;
			while ((length = reader.read(buf)) > 0) {
				sb.append(buf, 0, length);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
//    } catch (NoSuchAlgorithmException e) {
//      e.printStackTrace();
		}
		return sb.toString();
	}

	public static String postData(String url, String data,String minType) {
		try {
			HttpEntity entity = Request.Post(url)
					.bodyString(data, ContentType.create(minType, Consts.UTF_8.name()))
					.execute().returnResponse().getEntity();
			if (entity != null) {
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				entity.writeTo(byteArrayOutputStream);
				return byteArrayOutputStream.toString(Consts.UTF_8.name());
			}
			return null;
		} catch (Exception e) {
			logger.error("post请求异常，" + e.getMessage() + "\npost url:" + url);
			e.printStackTrace();
		}
		return null;
	}


	public static Map<String,Object> postDataReturnData(String url, String data,String minType) {
		Map<String,Object> map=new HashMap<String,Object>();
		try {
			HttpResponse response=Request.Post(url).bodyString(data,ContentType.create(minType, Consts.UTF_8.name())).execute().returnResponse();
			int responseCode=response.getStatusLine().getStatusCode();
			HttpEntity entity=response.getEntity();
			map.put("responseCode",responseCode);
			if (entity != null) {
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				entity.writeTo(byteArrayOutputStream);
				map.put("data",byteArrayOutputStream.toString(Consts.UTF_8.name()));
				//return map;
			}
			return map;
		} catch (Exception e) {
			logger.error("post请求异常，" + e.getMessage() + "\npost url:" + url);
			map.put("responseCode",1000);   //系统异常定义的代码code
			map.put("data",e.getMessage());
			e.printStackTrace();
		}
		return map;
	}

	public static InputStream getInputStream(String strUrl)
	{
		InputStream is=null;
		try {
			URL url = new URL(strUrl);
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			uc.setConnectTimeout(10000);//设置链接超时时间
			uc.setReadTimeout(10000);//设置读取超时时间
			if (uc.getResponseCode() == 200) {
				is=uc.getInputStream();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return is;
	}



}
